package ui;

import com.nanosl.lib.date.JXDatePicker;
import java.awt.event.KeyEvent;
import util.SuperView;
import ent.Employee;
import ent.Item;
import ent.PriceList;
import ent.SrStock;
import ent.SrStockPK;
import ent.Stock;
import ent.StockTransfer;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyAdapter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author t
 */
public final class StockTransferView extends SuperView {

    private static StockTransferView instance = new StockTransferView();

    public static void display() {
        instance.setVisible(true);
    }

    public static StockTransferView getInstance() {
        return instance;
    }

    /**
     * Creates new form BankView
     */
    public StockTransferView() {
        super();
        onLoad();
    }

    private StockTransferView(JFrame jFrame, boolean b) {
        this();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        repComboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        transferButton = new javax.swing.JButton();
        datePicker = new JXDatePicker();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        itemComboBox = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        quantityTextField = new javax.swing.JTextField();
        clearButton = new javax.swing.JButton();
        quantityLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("STOCK TRANSFER");

        masterTable.setAutoCreateRowSorter(true);
        masterTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "#", "Code", "Description", "Quantity", "Rate"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        masterTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                masterTableMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                masterTableMouseReleased(evt);
            }
        });
        masterTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                masterTableKeyReleased(evt);
            }
        });
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(0).setResizable(false);
        masterTable.getColumnModel().getColumn(0).setPreferredWidth(3);
        masterTable.getColumnModel().getColumn(0).setCellRenderer(rightAlignCell);
        masterTable.getColumnModel().getColumn(1).setResizable(false);
        masterTable.getColumnModel().getColumn(1).setPreferredWidth(5);
        masterTable.getColumnModel().getColumn(2).setResizable(false);
        masterTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        masterTable.getColumnModel().getColumn(3).setResizable(false);
        masterTable.getColumnModel().getColumn(3).setPreferredWidth(5);
        masterTable.getColumnModel().getColumn(3).setCellRenderer(rightAlignCell);
        masterTable.getColumnModel().getColumn(4).setResizable(false);
        masterTable.getColumnModel().getColumn(4).setPreferredWidth(6);
        masterTable.getColumnModel().getColumn(4).setCellRenderer(rightAlignCell);

        repComboBox.setName("repComboBox"); // NOI18N
        repComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                repComboBoxActionPerformed(evt);
            }
        });
        repComboBox.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                repComboBoxKeyPressed(evt);
            }
        });

        jLabel1.setText("Rep:");

        transferButton.setText("Transfer");
        transferButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                transferButtonActionPerformed(evt);
            }
        });

        datePicker.setName("datePicker"); // NOI18N
        datePicker.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                datePickerKeyPressed(evt);
            }
        });

        jLabel2.setText("Date:");

        jLabel3.setText("Item:");

        itemComboBox.setName("itemComboBox"); // NOI18N
        itemComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemComboBoxActionPerformed(evt);
            }
        });
        itemComboBox.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                itemComboBoxKeyPressed(evt);
            }
        });

        jLabel4.setText("Quantity:");

        quantityTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quantityTextFieldActionPerformed(evt);
            }
        });

        clearButton.setText("Clear");
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });

        quantityLabel.setText("0");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(itemComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(quantityLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(quantityTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(repComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(44, 44, 44)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                        .addComponent(datePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(clearButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 331, Short.MAX_VALUE)
                        .addComponent(transferButton)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(repComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2))
                    .addComponent(datePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(itemComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(quantityTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(quantityLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 416, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(clearButton)
                    .addComponent(transferButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
    }//GEN-LAST:event_masterTableMouseClicked

    private void masterTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_masterTableKeyReleased
        if (evt.getKeyCode() == 127) {
            tableModel.removeRow(masterTable.getSelectedRow());
        }
    }//GEN-LAST:event_masterTableKeyReleased

    private void masterTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseReleased
    }//GEN-LAST:event_masterTableMouseReleased

    private void repComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_repComboBoxActionPerformed
        datePicker.requestFocus();
    }//GEN-LAST:event_repComboBoxActionPerformed

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
        clear();
    }//GEN-LAST:event_clearButtonActionPerformed

    private void quantityTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quantityTextFieldActionPerformed
        fillTable();

    }//GEN-LAST:event_quantityTextFieldActionPerformed

    private void itemComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemComboBoxActionPerformed
        setQuantity();
    }//GEN-LAST:event_itemComboBoxActionPerformed

    private void itemComboBoxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_itemComboBoxKeyPressed
        if (evt.getKeyCode() == 10 && !quantityLabel.getText().equals("0")) {
            quantityTextField.requestFocus();
        }
    }//GEN-LAST:event_itemComboBoxKeyPressed

    private void transferButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_transferButtonActionPerformed
        if (tableModel.getRowCount() > 0) {
            transfer();
        }
    }//GEN-LAST:event_transferButtonActionPerformed

    private void datePickerKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_datePickerKeyPressed
        if (evt.getKeyCode() == 10) {
            itemComboBox.requestFocus();
        }
    }//GEN-LAST:event_datePickerKeyPressed

    private void repComboBoxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_repComboBoxKeyPressed
        if (evt.getKeyCode() == 10) {
            datePicker.requestFocus();
        }
    }//GEN-LAST:event_repComboBoxKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                StockTransferView dialog = new StockTransferView();
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clearButton;
    private org.jdesktop.swingx.JXDatePicker datePicker;
    private javax.swing.JComboBox itemComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JLabel quantityLabel;
    private javax.swing.JTextField quantityTextField;
    private javax.swing.JComboBox repComboBox;
    private javax.swing.JButton transferButton;
    // End of variables declaration//GEN-END:variables
    DefaultTableModel tableModel;

    private void fillTable() {
        double quantity = 0;
        try {
            quantity = Double.valueOf(quantityTextField.getText().trim());
            double availablaQuantity = Double.valueOf(quantityLabel.getText().trim());
            if (quantity > availablaQuantity) {
                setStatusMessage("Quantity Not Enough", Color.RED);
                return;
            }
        } catch (Exception e) {
            setStatusMessage("Invalid Quantity Value", Color.RED);
            return;
        }
        Item item = (Item) itemComboBox.getSelectedItem();
        if (item == null) {
            return;
        }
        Employee rep = (Employee) repComboBox.getSelectedItem();
        SrStockPK srStockPK = new SrStockPK(rep.getCode(), item.getCode());
        SrStock srStock = m.find(SrStock.class, srStockPK);
        if (srStock == null) {
            srStock = new SrStock(srStockPK);
            srStock.setBundles(0.0);
            srStock.setEmployee(rep);
            srStock.setItem(item);
            srStock.setPackPrice(item.getPriceList().getSellingPack());
            srStock.setQuantity(0.0);
            srStock.setUnitPrice(item.getPriceList().getSellingUnit());
            m.update(srStock);
            srStock = m.find(SrStock.class, srStockPK);
        }
        int i = tableModel.getRowCount();
        double rate = srStock.getPackPrice() == null ? 0.0 : srStock.getPackPrice();
        Object[] row = {++i, item.getCode(), item.getDescription(), nf3d.format(quantity), nf2d.format(rate)};
        tableModel.addRow(row);

        quantityTextField.setText("");
        itemComboBox.requestFocus();
    }

    protected void onLoad() {
        initComponents();
        tableModel = (DefaultTableModel) masterTable.getModel();
        KeyAdapter();
    }

    private void KeyAdapter() {
        AutoCompleteDecorator.decorate(repComboBox);
        AutoCompleteDecorator.decorate(itemComboBox);
        setComboBoxKeyAdapters(repComboBox);
        setComboBoxKeyAdapters(itemComboBox);
        setComboBoxKeyAdapters(datePicker);
    }

    private void setComboBoxKeyAdapters(JComponent comp) {
        String compName = comp.getName();
        if (compName == null) {
            return;
        }
        Component component[] = comp.getComponents();
        for (int i = 0; i < component.length; i++) {
            if (compName.equals("repComboBox")) {
                component[i].addKeyListener(repComboBoxKeyAdapter);
            } else if (compName.equals("itemComboBox")) {
                component[i].addKeyListener(itemComboBoxKeyAdapter);
            } else if (compName.equals("datePicker")) {
                component[i].addKeyListener(datePickerKeyAdapter);
            }
        }
    }
    KeyAdapter datePickerKeyAdapter = new java.awt.event.KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent evt) {
            datePickerKeyPressed(evt);
        }
    };
    KeyAdapter itemComboBoxKeyAdapter = new java.awt.event.KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent evt) {
            itemComboBoxKeyPressed(evt);
        }
    };
    KeyAdapter repComboBoxKeyAdapter = new java.awt.event.KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent evt) {
            repComboBoxKeyPressed(evt);
        }
    };

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        clear();
    }

    private void fillItems() {
        itemComboBox.setModel(new DefaultComboBoxModel(m.find(Item.class).toArray()));
    }

    private void fillReps() {
        repComboBox.setModel(new DefaultComboBoxModel(m.find(Employee.class).toArray()));
    }

    private void clear() {
        fillItems();
        fillReps();
        tableModel.setRowCount(0);
        quantityLabel.setText("0");
    }

    private void transfer() {
        Date date = datePicker.getDate();
        if (date == null) {
            setStatusMessage("Date Required", Color.RED);
            return;
        }
        List<Serializable> serializables = new ArrayList<Serializable>();
        Employee rep = (Employee) repComboBox.getSelectedItem();
        for (int i = 0; i < tableModel.getRowCount(); i++) {
            Item item = m.find(Item.class, tableModel.getValueAt(i, 1).toString());
            Stock stock = item.getStock();
            double quantity = Double.valueOf(tableModel.getValueAt(i, 3).toString());
            double rate = Double.valueOf(tableModel.getValueAt(i, 4).toString());
            stock.setQuantity(stock.getQuantity() - quantity);
            StockTransfer stockTransfer = new StockTransfer(rep.getCode(), item.getCode(), date);
            stockTransfer.setQuantity(quantity);
            stockTransfer.setEmployee(rep);
            stockTransfer.setItem(item);
            stockTransfer.setRate(rate);
            PriceList priceList = item.getPriceList();
            if (priceList == null) {
                priceList = new PriceList(item.getCode());
                priceList.setCostPack(0.0);
                priceList.setCostUnit(0.0);
                priceList.setItem(item);
                priceList.setSellingPack(0.0);
                priceList.setSellingUnit(0.0);
                serializables.add(priceList);
            }
            SrStockPK srStockPK = new SrStockPK(rep.getCode(), item.getCode());
            SrStock srStock = m.find(SrStock.class, srStockPK);
            if (srStock == null) {
                srStock = new SrStock(srStockPK);
                srStock.setItem(item);
                srStock.setEmployee(rep);
                srStock.setQuantity(quantity);
                srStock.setPackPrice(priceList.getSellingPack());
                srStock.setUnitPrice(priceList.getSellingUnit());
            } else {
                srStock.setQuantity(srStock.getQuantity() + quantity);
            }
            serializables.add(stock);
            serializables.add(stockTransfer);
            serializables.add(srStock);
        }
        if (m.update(serializables)) {
            setStatusMessage("Update Success");
            clear();
            return;
        }
        showError("Update Failed");
    }

    private void setQuantity() {
        quantityLabel.setText("0");
        Item item = (Item) itemComboBox.getSelectedItem();
        Stock stock = item.getStock();
        if (stock == null) {
            stock = new Stock(item.getCode());
            stock.setBundles(0.0);
            stock.setItem(item);
            stock.setQuantity(0.0);
            item.setStock(stock);
            m.update(stock);
            m.update(item);
        }
        quantityLabel.setText(nf3d.format(stock.getQuantity()));
    }
}
